package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsProduct;
import com.bwie.pojo.Image;
import com.bwie.pojo.Product;
import com.bwie.service.ImageService;
import com.bwie.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class EsProductTask {

    @Autowired
    private ProductService productService;


    @Autowired
    private ImageService imageService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Scheduled(cron = "0/30 * * * * ?")
    public void task(){
        System.out.println("开启同步");
        List<Product> productList = productService.productList();
        List<Image> images = imageService.list();
        for (Product product : productList) {
            ArrayList<Image> list = new ArrayList<>();
            for (Image image : images) {
                if (image.getProductId() == product.getId()){
                    list.add(image);
                }
            }
            product.setImageList(list);
            EsProduct esProduct = BeanUtil.toBean(product, EsProduct.class);
            elasticsearchRestTemplate.save(esProduct);
        }
        System.out.println("关闭同步");
    }

}
